package com.dididoctor.doctor.Activity.splash;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dididoctor.doctor.Activity.Login.DisclaimerActivity;
import com.dididoctor.doctor.Activity.Login.loginActivity;
import com.dididoctor.doctor.Activity.Usercentre.Authentication.AuthenticationActivity;
import com.dididoctor.doctor.Activity.mvp.MainActivity;
import com.dididoctor.doctor.Bean.AppVersion;
import com.dididoctor.doctor.Dialog.UpdatView;
import com.dididoctor.doctor.Dialog.UpdateDialog;
import com.dididoctor.doctor.MV.EduActivity;
import com.dididoctor.doctor.R;
import com.dididoctor.doctor.Ui.numberprogressbar.NumberProgressBar;
import com.dididoctor.doctor.Utils.SharedPreferencesUtils;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import java.io.File;


/**
 * @version 2.0
 * @类描述： 起始页
 * @项目名称：douDouTech
 * @类名称： SplashActivity
 * @包名称： com.doudoukeji.service.Activity.splash
 * @创建人：张强 boy
 * @创建时间：2016/3/7 16:40
 * @修改人：
 * @修改时间：2016/3/7 16:40
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class SplashActivity extends EduActivity implements SplashView, UpdatView {

    protected static final String TAG = "SplashActivity";
    private TextView mTvSplashUpDataInfo, mTvVersionCode;
    //动画时间间隔
    private int firstDuration, secondDuration, thirdDuration = 0;// 需要的时候 3000 2000 1000
    //四个字的图片
//    private ImageView  mIvFirst, mIvSecond, mIvThird, mIvForth;
    //存放四张文字图片的图片集合
//    private ImageView[] images;

    private int curImage = 0;

    private SplashPresenter presenter;

    //提醒更新对话框
    private UpdateDialog dialog;

    //更新apk进度条
    private NumberProgressBar mNumberProgressBar;
    private ProgressBar mProgressHorizontalColor;
    private TextView mTvShowSynchronousData;
    private ImageView splash_anim;
    private AnimationDrawable animationDrawable;
    private  int duration = 0;


    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_splash);
    }

    @Override
    public void init() {

        //初始化控件操作
        initView();

        //初始化数据
        initData();

    }

    /**
     * 初始化数据
     */
    private void initData() {

        if (SharedPreferencesUtils.getParam(SplashActivity.this,
                "isFirst", "0").equals("0")) {
            firstDuration = 1500;
            secondDuration = 1000;
            thirdDuration = 500;
        }

        mTvVersionCode.setText( getVersion());

        //开启启动页动画
//        startAnimation(mIvLogo);


    }

    /**
     * 获取当前应用程序的版本号
     *
     * @return 版本号
     */
    public String getVersion() {
        // 包管理器，用于获取应用程序包信息
        PackageManager pm = getPackageManager();
        try {
            // PackageInfo代表的就是清单文件的信息
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            String versionName = packageInfo.versionName;
            return versionName; // versionName属性的值
        } catch (PackageManager.NameNotFoundException e) {
            // can't reach 肯定不会发生，因为getPackageName()
            e.printStackTrace();
            return "0";
        }
    }


    /**
     * 显示更新提醒对话框
     *
     * @param appVersionBean
     */
    private void showUpdateDialog(AppVersion appVersionBean) {
        dialog = new UpdateDialog(SplashActivity.this, SplashActivity.this, appVersionBean);
        dialog.show();
    }

    /**
     * 初始化控件操作
     */
    private void initView() {
        mTvSplashUpDataInfo = (TextView) findViewById(R.id.tv_splash_updateinfo);
//        mIvLogo = (ImageView) findViewById(R.id.iv_logo);
//        mIvFirst = (ImageView) findViewById(R.id.iv_first);
//        mIvSecond = (ImageView) findViewById(R.id.iv_second);
//        mIvThird = (ImageView) findViewById(R.id.iv_third);
//        mIvForth = (ImageView) findViewById(R.id.iv_forth);

        //初始化更新apk进度条
        mNumberProgressBar = (NumberProgressBar) findViewById(R.id.numberProgressBar);
        mProgressHorizontalColor = (ProgressBar) findViewById(R.id.progress_horizontal_color);
        mTvShowSynchronousData = (TextView) findViewById(R.id.tv_showsynchronousdata);
//        images = new ImageView[]{mIvFirst, mIvSecond, mIvThird, mIvForth};
        mTvVersionCode = (TextView) findViewById(R.id.tv_versioncode);

        splash_anim = (ImageView) findViewById(R.id.splash_anim);
        splash_anim.setImageResource(R.drawable.spalsh_anim);
        animationDrawable = (AnimationDrawable) splash_anim.getDrawable();
        animationDrawable.start();


        for(int i=0;i<animationDrawable.getNumberOfFrames();i++){
            duration += animationDrawable.getDuration(i);
        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                presenter = new SplashPresenter(SplashActivity.this, SplashActivity.this);
                presenter.launch();
            }
        }, duration);

    }


    @Override
    public void onClickEvent(View view) {

    }


    /**
     * 开启图片文字渐变位移动画
     *
     * @param img
     */
//    public void startAnimation(final ImageView img) {
//        AnimationSet as = new AnimationSet(true);
//        AlphaAnimation ani = new AlphaAnimation(0, 1);
//        ani.setDuration(firstDuration);
//        ani.setAnimationListener(new Animation.AnimationListener() {
//
//            public void onAnimationStart(Animation animation) {
//                setAlphaAnimation();
//            }
//
//            public void onAnimationEnd(Animation animation) {
//                TranslateAnimation trans = new TranslateAnimation(0, 0, 0, -200);
//                trans.setDuration(secondDuration);
//                trans.setFillAfter(true);
//                trans.setAnimationListener(new Animation.AnimationListener() {
//
//                    @Override
//                    public void onAnimationStart(Animation animation) {
//                        // TODO Auto-generated method stub
//
//                    }
//
//                    @Override
//                    public void onAnimationRepeat(Animation animation) {
//                        // TODO Auto-generated method stub
//
//                    }
//
//                    @Override
//                    public void onAnimationEnd(Animation animation) {
//                        setAlpha(images[curImage]);
//                    }
//                });
//                img.startAnimation(trans);
//            }
//
//            public void onAnimationRepeat(Animation animation) {
//                // TODO Auto-generated method stub
//
//            }
//
//        });
//        as.addAnimation(ani);
//        img.startAnimation(as);
//    }

    /**
     * @param image
     */
//    public void setAlpha(final ImageView image) {
//
//        AnimationSet as = new AnimationSet(true);
//        AlphaAnimation ani = new AlphaAnimation(0, 1);
//        ani.setDuration(thirdDuration);
//        ani.setAnimationListener(new Animation.AnimationListener() {
//
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            public void onAnimationEnd(Animation animation) {
//                curImage++;
//                if (curImage <= 3) {
//                    setAlpha(images[curImage]);
//                } else {
//                    // 检查版本号信息
//                    presenter = new SplashPresenter(SplashActivity.this, SplashActivity.this);
//                    presenter.launch();
//                }
//            }
//
//            public void onAnimationRepeat(Animation animation) {
//                // TODO Auto-generated method stub
//
//            }
//
//        });
//        as.addAnimation(ani);
//        image.startAnimation(as);
//    }


    /**
     * 设置透明动画
     */
//    public void setAlphaAnimation() {
//        for (int i = 0; i < images.length; i++) {
//            AlphaAnimation ani2 = new AlphaAnimation(0, 0);
//            ani2.setDuration(0);
//            ani2.setFillAfter(true);
//            images[i].startAnimation(ani2);
//        }
//
//    }
    @Override
    public void intentGuideActivity() {
        Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void intentLoginActitity() {
        Intent intent = new Intent(SplashActivity.this, loginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void intentMainActivity() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void tipUpdataDiolag(AppVersion appVersionBean) {
        showUpdateDialog(appVersionBean);
    }

    @Override
    public void intentEditmessageActivity() {
//        Intent intent = new Intent(SplashActivity.this, EditMessageActivity.class);
//        startActivity(intent);
//        finish();
    }

    @Override
    public void initentDisclaimerActivity() {
        Intent intent = new Intent(SplashActivity.this, DisclaimerActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void initentAuthenticationActivity() {
        Intent intent = new Intent(SplashActivity.this, AuthenticationActivity.class);
        startActivity(intent);
        finish();

    }

    /**
     * 跳转界面
     *
     * @param Activityclass
     */
    private void IntentActivity(Class Activityclass) {
        Intent intent = new Intent(this, Activityclass);
        startActivity(intent);
        finish();
    }

    @Override
    public void update(String path) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // 下载新的apk，下载路径path；使用开源jar包afinal_0.5_bin.jar
            FinalHttp fh = new FinalHttp();
            fh.configTimeout(60 * 1000);
            fh.download(path, Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/update1.apk",
                    new AjaxCallBack<File>() {
                        @Override
                        public void onFailure(Throwable t, int errorNo,
                                              String strMsg) {
                            Toast.makeText(getApplicationContext(), "更新失败", Toast.LENGTH_SHORT)
                                    .show();
                            IntentActivity(loginActivity.class);
                            super.onFailure(t, errorNo, strMsg);
                        }

                        @Override
                        public void onLoading(long count, long current) {
                            super.onLoading(count, current);
                            if (current >= count) {
                                mNumberProgressBar.setVisibility(View.INVISIBLE);
                            } else {
                                mNumberProgressBar.setVisibility(View.VISIBLE);
                            }
                            mNumberProgressBar.setProgress((int) ((float) current / (float) count * 100f));
                            int progress = (int) (current * 100 / count);
                            mTvSplashUpDataInfo.setText("正在下载:" + progress
                                    + "%");
                        }

                        @Override
                        public void onSuccess(File t) {
                            super.onSuccess(t);
                            mTvSplashUpDataInfo.setText("下载完毕");
                            installApk(t);
                        }

                        /**
                         * 安装一个apk文件，调用系统安装应用PackageInstaller
                         *
                         * @param
                         */
                        private void installApk(File t) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setDataAndType(Uri.fromFile(t),
                                    "application/vnd.android.package-archive");
                            startActivity(intent);
                        }

                    });
        } else {
            Toast.makeText(getApplicationContext(), "sd卡不可用，更新失败", Toast.LENGTH_SHORT).show();
            IntentActivity(loginActivity.class);
            return;
        }
    }

    @Override
    public void unUpDate() {
        IntentActivity(loginActivity.class);
    }

    @Override
    public void ShowSynchronousData() {
//        mProgressHorizontalColor.setVisibility(View.VISIBLE);
//        mProgressHorizontalColor.setIndeterminate(true);
//        mTvShowSynchronousData.setVisibility(View.VISIBLE);
//        mTvShowSynchronousData.setText("正在同步数据....");
    }

    @Override
    public void DissSynchronousData() {

//        mProgressHorizontalColor.setVisibility(View.VISIBLE);
//        mProgressHorizontalColor.setIndeterminate(true);
//        mTvShowSynchronousData.setVisibility(View.VISIBLE);
//        mTvShowSynchronousData.setText("同步完毕");
//        mTvShowSynchronousData.setTextColor(Color.parseColor("#ffffff"));
    }

    @Override
    public void ErrorSynchronousData() {
//        mProgressHorizontalColor.setVisibility(View.VISIBLE);
//        mProgressHorizontalColor.setIndeterminate(true);
        mTvShowSynchronousData.setVisibility(View.VISIBLE);
        mTvShowSynchronousData.setText("同步数据失败，请检测网络");
        mTvShowSynchronousData.setTextColor(Color.RED);
    }
}
